import Request from './request/request'
import { BASE_URL, TIME_OUT } from './request/config'
import { errorResponse } from './request/type'
import { localCache } from '@/utils'

function callBackPopout(errorResponse: errorResponse) {
  const { status, data } = errorResponse
  switch (status) {
    case 400:
      ElMessage.error(data)
      break
    case 401:
      ElMessage.error(data)
      break
    case 403:
      ElMessage.error(data)
      break
    case 404:
      ElMessage.error(data)
      break
    case 405:
      ElMessage.error(data)
      break
    case 500:
      ElMessage.error(data || '服务器遇到错误，无法完成请求。')
      break
    default:
      ElMessage({
        message: '请稍后~~~',
        type: 'warning'
      })
      break
  }
}
export default new Request({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  interceptors: {
    // 每个实例都会有一个拦截器
    requestInterceptor: (config) => {
      // 将token携带到header里面
      const token = localCache.getCache('token')

      if (token) {
        // config可能为undefined
        if (config && config.headers) {
          config.headers.Authorization = `Bearer ${token}`
        }
      }
      // console.log('请求成功的拦截', config)
      return config
    },
    requestInterceptorCatch: (error) => {
      return error
    },
    responseInterceptor: (config) => {
      // console.log('响应成功拦截', config)
      return config
    },
    responseInterceptorCatch: (error) => {
      console.log(error, 'error')

      callBackPopout(error.response)
      // console.log('响应失败拦截', error, '1')
      return error
    }
  }
})
